import { App } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
import defaultImg from '@/assets/images/200.png'

export default {
  install(app: App) {
    app.directive('lazy', {
      // el => v-lazy 写到哪儿，el 就是谁
      // v-lazy="xxx" => binding.value => xxx
      mounted(el: HTMLImageElement, binding) {
        const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
          if (isIntersecting) {
            // 把传过来的地址给图片真正的 src 属性
            el.src = binding.value
            // 加载失败给一个默认图片
            el.onerror = function () {
              this.src = defaultImg
            }
            // 停止监听
            stop()
          }
        })
      },
    })
  },
}
